#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib,urllib2,re,os,cookielib,xbmc

#author:
#elypter
#-mail:elypter@yahoo.de
#
#for details look at default.py

#duckload.com/youload.com-plugin for the iload.to-plugin
debug=1
dstr=""

def check(url):
	if url.rfind("duckload") or url.rfind("youload"):
		return 1
	else:
		return 0

def get_regexp():
	#return "(?:http\://www\.megavideo\.com/v/([A-Z]+)[0-9a-z]*|http\://www\.megavideo\.com/\?v\=([0-9a-z]*))"
	return "(http://duckload.com(?:/divx){0,1}/[0-9a-zA-Z]*.html|http://youload.to(?:/divx){0,1}/[0-9a-zA-Z]*.html)"
def get_name():
	return "duckload"
def join(id):
	return id
	
def get_link1(url):
	#takes an videopage-url of duckload
	#
	#returnes the service/mirror name, the url that will be passed over to get_link2, the url of the verification code
	if url.rfind("duckload.com") != -1:
		domain="duckload.com"
	elif url.rfind("youload.to") != -1:
		domain="youload.to"
	else:
		print "error"
		
	BASE_PATH = os.getcwd().replace( ";", "" )
	BASE_DATA_PATH = os.path.join( xbmc.translatePath("special://profile/plugin_data/hoster"), "oracle2" )
	if not os.path.isdir(BASE_DATA_PATH):
		if os.path.exists(BASE_DATA_PATH):
			if debug > -1: print dstr+"*hoster*oracle*duckload*get_link1* creating folder >>> delete this file! : "+BASE_DATA_PATH
		os.makedirs(BASE_DATA_PATH)
		
	cookiefile = os.path.join(BASE_DATA_PATH,"duckload.lwp")
	cj = cookielib.LWPCookieJar()
	if os.path.isfile(cookiefile):
		cj.load(cookiefile)
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
	urllib2.install_opener(opener)
	#cj.clear()
	
	#req = urllib2.Request(url=url,origin_req_host="duckload.com")
	print url
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2')
	response = urllib2.urlopen(req)
	page=response.read()
	response.close()
	cj.save(cookiefile)
	
	match=re.compile('type="video/divx" src="([^<>"]*)"').findall(page)
	if not len(match)>0:
		#match=re.compile('src="/design/Captcha2\.php\?wmid=1337\&Sec=([a-zA-Z0-9]*)\&nob=true"').findall(page)
		match=re.compile("/design/Captcha2\.php\?wmid\=1337\&Sec\=([a-zA-Z0-9]*)\&nob\=true\&Reload\=").findall(page)
		if len(match)>0:
			if match[0]!="":
				filename=os.path.join(BASE_DATA_PATH,match[0][10:20]+".png")
				if os.path.exists(filename):
					#os.remove(filename)
					print "nothing"
				#getting the captcha (WITH) using a cookie (otherwise you get a random captcha)
				#req = urllib2.Request('http://'+domain+'/design/Captcha2.php?wmid=1337&key='+match[0]+'&nob=true')
				req = urllib2.Request('http://'+domain+'/design/Captcha2.php?wmid=1337&Sec='+match[0]+'&nob=true&Reload=')
				req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2')
				req.add_header("Referer", 'http://'+domain+'/c'+match[0]+'.html')
				r =	urllib2.urlopen(req)
				fd=open(filename, "w" )
				fd.write(r.read()) 
				fd.close()
				
				#cj.save(cookiefile)
				#return ("duckload","http://duckload.com/c"+match[0]+".html",filename)
				return ("captcha","http://"+domain+"/c"+match[0]+".html",'','','',filename,'duckload')
		else:
			#cj.save(cookiefile)
			#return ("duckload",url,'')
			return ("fail",url,'','','','','duckload')
	#cj.save(cookiefile)
	#return ("duckload",match[0],'')
	return ("got",match[0],'','','','','duckload')
	
	#return #status,link,image,title,filename,captcha,hoster	
	
	
	
def get_link2(url1,code):
	#should take the url that get_link1 returned
	#
	#returnes the video url
	
	BASE_PATH = os.getcwd().replace( ";", "" )
	BASE_DATA_PATH = os.path.join( xbmc.translatePath("special://profile/plugin_data/hoster"), "oracle2" )
	if not os.path.isdir(BASE_DATA_PATH):
		if os.path.exists(BASE_DATA_PATH):
			if debug > -1: print dstr+"*hoster*oracle*duckload*get_link1* creating folder >>> delete this file! : "+BASE_DATA_PATH
		os.makedirs(BASE_DATA_PATH)
		
		
	cookiefile = os.path.join(BASE_DATA_PATH,"duckload.lwp")
	cj = cookielib.LWPCookieJar()
	if os.path.isfile(cookiefile):
		cj.load(cookiefile)
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
	urllib2.install_opener(opener)
	
	print "cooooooooookies"
	for index, cookie in enumerate(cj):
		print index, '  :  ', cookie
	
	values = {'server' : urllib.unquote('1'),
			#urllib.unquote('appl_code') : urllib.unquote(code)} 
			urllib.unquote('a_code') : urllib.unquote(code)} 
	data = urllib.urlencode(values)
	
	req = urllib2.Request(url1,data)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2')
	response = urllib2.urlopen(req)
	page=response.read()
	response.close()
	
	
	match=re.compile('type="video/divx" src="([^<>"]*)"').findall(page)
		
	if len(match)>0:
		#return match[0]
		return ("got",match[0],'','','','','duckload')
	else:
		#return ""
		return ("wrongcaptcha",'','','','','','duckload')